package com.neusoft.yiyang.care.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.yiyang.care.client.CustomerClient;
import com.neusoft.yiyang.care.client.UserClient;
import com.neusoft.yiyang.common.entity.care.CareRecord;
import com.neusoft.yiyang.care.mapper.CareRecordMapper;
import com.neusoft.yiyang.care.service.CareRecordService;
import com.neusoft.yiyang.common.enums.ExecutionStatus;
import com.neusoft.yiyang.common.exception.BusinessException;
import com.neusoft.yiyang.common.utils.OssUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

@Service
public class CareRecordServiceImpl implements CareRecordService {

    @Autowired
    private CareRecordMapper careRecordMapper;

    @Autowired
    private OssUploadUtils ossUploadUtils;

    @Override
    public List<CareRecord> getCareRecordsByCustomerId(Integer customerId) {
        LambdaQueryWrapper<CareRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CareRecord::getCustomerId, customerId) // 按客户ID筛选
                .orderByDesc(CareRecord::getCareTime); // 按护理时间倒序
        return careRecordMapper.selectList(wrapper);
    }

    @Override
    public List<CareRecord> getCareRecordsByCaretakerId(Integer caretakerId) {
        LambdaQueryWrapper<CareRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CareRecord::getCaretakerId, caretakerId) // 按护工ID筛选
                .orderByDesc(CareRecord::getCareTime); // 按护理时间倒序
        return careRecordMapper.selectList(wrapper);
    }

    @Override
    public void updateCareRecord(
            Integer careRecordId,
            Integer careItemId,
            Integer caretakerId,
            Date careTime,
            Integer quantity,
            String feedback,
            String status,
            MultipartFile file
    ) {
        // 1. 校验原记录是否存在
        CareRecord originalRecord = careRecordMapper.selectById(careRecordId);
        if (originalRecord == null) {
            throw new BusinessException(404, "护理记录不存在");
        }

        // 2. 处理文件上传（如果有新照片）
        String photoUrl = originalRecord.getPhotoUrl(); // 默认保留原照片
        if (file != null && !file.isEmpty()) {
            String folder = "care-photos/" + LocalDate.now();
            photoUrl = ossUploadUtils.uploadFile(file, folder);
        }

        // 3. 更新字段（不为null的参数才更新）
        if (careItemId != null) {
            originalRecord.setCareItemId(careItemId);
        }
        if (caretakerId != null) {
            originalRecord.setCaretakerId(caretakerId);
        }
        if (careTime != null) {
            originalRecord.setCareTime(careTime);
        }
        if (quantity != null) {
            originalRecord.setQuantity(quantity);
        }
        if (feedback != null) {
            originalRecord.setFeedback(feedback);
        }
        if (status != null) {
            originalRecord.setStatus(ExecutionStatus.valueOf(status));
        }
        originalRecord.setPhotoUrl(photoUrl); // 更新照片URL

        // 4. 保存更新
        careRecordMapper.updateById(originalRecord);
    }

    @Override
    public void deleteCareRecord(Integer careRecordId) {
        careRecordMapper.deleteById(careRecordId);
    }

    @Override
    public Page<CareRecord> pageQuery(Page<CareRecord> page,
                                      String customerName,
                                      String caretakerName,
                                      Date startDate,
                                      Date endDate,
                                      String careItemName,
                                      Integer caretakerId,
                                      String status) {
        LambdaQueryWrapper<CareRecord> wrapper = new LambdaQueryWrapper<>();

        if (customerName != null && !customerName.isEmpty()) {
            wrapper.apply("exists (select 1 from customer c where c.customer_id = care_record.customer_id and c.customer_name like concat('%', {0}, '%'))", customerName);
        }

        if (caretakerName != null && !caretakerName.isEmpty()) {
            wrapper.apply("exists (select 1 from user u where u.user_id = care_record.caretaker_id and u.name like concat('%', {0}, '%'))", caretakerName);
        }

        if (startDate != null) {
            wrapper.ge(CareRecord::getCareTime, startDate);
        }
        if (endDate != null) {
            wrapper.le(CareRecord::getCareTime, endDate);
        }

        if (careItemName != null && !careItemName.isEmpty()) {
            wrapper.apply("exists (select 1 from care_item ci where ci.care_item_id = care_record.care_item_id and ci.item_name like concat('%', {0}, '%'))", careItemName);
        }

        if (caretakerId != null) {
            wrapper.eq(CareRecord::getCaretakerId, caretakerId);
        }

        if (status != null && !status.isEmpty()) {
            try {
                ExecutionStatus executionStatus = ExecutionStatus.valueOf(status);
                wrapper.eq(CareRecord::getStatus, executionStatus);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        // 添加按护理时间倒序
        wrapper.orderByDesc(CareRecord::getCareTime);

        // 执行分页查询
        return careRecordMapper.selectPage(page, wrapper);
    }

    @Override
    public List<CareRecord> getAllCareRecords() {
        LambdaQueryWrapper<CareRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(CareRecord::getCareTime); // 按护理时间倒序
        return careRecordMapper.selectList(wrapper);
    }

    @Override
    public CareRecord getCareRecordById(Integer careRecordId) {
        return careRecordMapper.selectById(careRecordId);
    }

}
